package com.markpim.algo;

public class InsertionSort {

	public InsertionSort(int[] input) {
		long timeSum = 0;
		for (int i = 0; i < Apl.ACCURACY; i++) { 
			assert Apl.isSorted(insertionSort(input)) : "Tried to insertionsort but failed!";
			timeSum += (endTime-startTime);
		}
		avgTime = timeSum/Apl.ACCURACY;
		
		done(input.length);
	}

	protected long startTime = 0;
	protected long endTime = 0;
	protected long avgTime = 0;
	protected long operations = 0;

	

	public void done(int count) {
		System.out.println("Insertionsorted " + count + " integers");

		System.out.println("Sorted in " + avgTime
				+ " milliseconds");
		System.out.println(operations/Apl.ACCURACY + " operations.");
		System.out.println(" -------------- ");
		System.out.println();
	}

	private int[] insertionSort(int[] numbers) {
		startTime = System.currentTimeMillis();

		for (int i = 0; i < numbers.length; i++) {
			operations++;
			int temp = numbers[i];
			int j = i;
			while (j > 0 && numbers[j - 1] >= temp) {
				operations++;
				numbers[j] = numbers[j - 1];
				j--;
			}
			numbers[j] = temp;

		}
		endTime = System.currentTimeMillis();

		return numbers;
	}

}
